package com.menu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.base.tree.Tree;
import com.base.tree.TreeNode;
import com.base.tree.TreeStyleType;

public class TreeMenu extends Tree{
	public TreeMenu(String containerId, String xmlFile) {
		super(containerId);
		
		load(xmlFile);
	}
	
	private void load(String xmlFile) {
		SAXBuilder builder = new SAXBuilder();
		try {
			Document document = builder.build("file:///" + xmlFile);
			Element root = document.getRootElement();
			String style = root.getAttributeValue("style");
			if("".equals(style) || null == style) {
				style = "style1";
			}
			this.setStyle(TreeStyleType.getType(style));
			load(root, Tree.rootNodeId);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void load(Element ele, String pid){
		List itemEles = ele.getChildren("item");
		
		if(itemEles == null  && itemEles.size() > 0) return;
		
		for(int i = 0; i < itemEles.size(); i++) {
			List<TreeNode> treeNodes = new ArrayList<TreeNode>();
			Element itemEle = (Element) itemEles.get(i);
			TreeNode node = new TreeNode(itemEle.getAttributeValue("name"));
			String href = itemEle.getAttributeValue("href");
			if(href == null) href = "";
			node.addInfo("href", href);
			if(itemEle.getChildren("item") != null && itemEle.getChildren("item").size() > 0) {
				node.setLeaf(false);
			}else {
				node.setLeaf(true);
			}
			
			treeNodes.add(node);
			this.addChildNodes(pid, treeNodes);
			
			load(itemEle, node.getId());
		}
	}

	@Override
	public List<TreeNode> getNodes(String pid) {
		List<TreeNode> nodes = new ArrayList<TreeNode>();
		TreeNode pNode = null;
		if(null == pid || "".equals(pid)) {
			pid = Tree.rootNodeId;
		}
		
		pNode = this.getNode(pid);
		
		nodes = Arrays.asList(pNode.getChildren()); // pNode.getChildren();
		
		return nodes;
	}

}
